<template>
  <div class="WorkOrderMain">
    <!-- 查询模块 -->
    <el-card class="box-card WorkOrderFrom">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="工单编号:">
          <el-input v-model.trim="addFrom.taskCode" clearable class="inputTop" placeholder="请输入" @change="getAllInfoFn" />
        </el-form-item>
        <el-form-item label="工单状态:">
          <el-select v-model="addFrom.status" clearable class="inputTop" placeholder="请选择" @change="getAllInfoFn">
            <el-option label="待办" value="1" />
            <el-option label="进行" value="2" />
            <el-option label="取消" value="3" />
            <el-option label="完成" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" class="inputTop searchBtn" @click="inquireFn">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card WorkOrderInfo">
      <!-- 表单内容 -->
      <el-button size="medium" class="addInfo" icon="el-icon-plus" @click="addInfo">新建</el-button>
      <el-button v-if="!addFrom.isRepair" size="medium" class="dispositionInfo" @click="configureThePopUpBoxFn">工单配置</el-button>
      <el-table ref="filterTable" :data="tableData" header-row-class-name="headerTab">
        <el-table-column label="序号" type="index" />
        <el-table-column prop="taskCode" label="工单编号" />
        <el-table-column prop="innerCode" label="设备编号" />
        <el-table-column prop="taskType.typeName" label="工单类型" />
        <el-table-column prop="cType" label="工单方式" />
        <el-table-column prop="taskStatusTypeEntity.statusName" label="工单状态" />
        <el-table-column prop="userName" label="运营人员" />
        <el-table-column prop="createTime" label="创建日期" />
        <el-table-column label="操作" width="100" class="text">
          <template #default="scope">
            <el-link type="primary" @click.native="seeDetails(scope.row)">查看详情</el-link>
          </template>
        </el-table-column>
      </el-table>
      <!-- 显示数据区域 -->
      <span class="dataInfo">共{{ total }}条记录  第 {{ addFrom.pageIndex }}/{{ parseInt(total/10) + 1 }} 页</span>
      <!-- 动态选择页面区域 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="addFrom.pageSize"
        :current-page="addFrom.pageIndex"
        hide-on-single-page
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 新增工单 -->
    <el-dialog
      title="新增工单"
      :visible.sync="addATicketDialogBox"
      width="35%"
    >
      <el-form ref="ruleForm" class="formText" :rules="formRules" :model="ruleForm" status-icon label-width="100px">
        <!-- 设备编号 -->
        <el-form-item label="设备编号:" prop="WorkOrderId" label-width="120px" style="width: 100%;">
          <el-input v-model.trim="ruleForm.WorkOrderId" type="text" placeholder="请输入" clearable @blur="getDialogueInfoFn(ruleForm.WorkOrderId)" />
        </el-form-item>
        <!-- 工单类型 -->
        <el-form-item label="工单类型:" prop="workorderStatus" label-width="120px" style="width: 100%;">
          <el-select v-model="ruleForm.workorderStatus" filterable placeholder="请选择">
            <el-option
              v-for="(item,index ) in workorderStatus"
              :key="index"
              :label="item.typeName"
              :value="item.typeName"
            />
          </el-select>
        </el-form-item>
        <!-- 补货数量 -->
        <el-form-item label=" 补货数量:" label-width="120px" style="width: 100%;">
          <el-link type="primary" :underline="false" @click="getVendingMachineDetailsFn">
            <i class="el-icon-edit-outline" clearable /> 补货清单
          </el-link>
        </el-form-item>
        <!-- 运营人员 -->
        <el-form-item label="运营人员:" prop="operationsStaff" label-width="120px" style="width: 100%;">
          <el-select v-model="ruleForm.operationsStaffsInfo" filterable placeholder="请选择">
            <el-option
              v-for="(item,index) in operationsStaffs"
              :key="index"
              :label="item.userName"
              :value="item.userName"
            />
          </el-select>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="备注" prop="remark" label-width="120px" style="width: 100%;">
          <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入备注（不超过40字）" maxlength="40" clearable resize="none" />
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addATicketDialogBox = false">取 消</el-button>
        <el-button type="primary" @click="submitFromInfoFn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 补货弹框 -->
    <el-dialog
      title="补货详情"
      :visible.sync="replenishmentPopUpFrame"
      width="35%"
    >
      <el-table :data="cargoAisleInfo" style="width: 100%" height="500">
        <!-- 货道编号 -->
        <el-table-column prop="channelCode" label="货道编号" />
        <!-- 商品名称 -->
        <el-table-column label="商品名称">
          <template #default="scope">
            {{ scope.row.sku?scope.row.sku.skuName:'-' }}
          </template>
        </el-table-column>
        <!-- 当前数量 -->
        <el-table-column prop="currentCapacity" label="当前数量">
          <template #default="scope">
            {{ scope.row.sku?scope.row.currentCapacity:'-' }}
          </template>
        </el-table-column>
        <!-- 还可添加 -->
        <el-table-column label="还可添加">
          <template #default="scope">
            {{ scope.row.sku?(scope.row.maxCapacity - scope.row.currentCapacity):'-' }}
          </template>
        </el-table-column>
        <!-- 补货数量 -->
        <el-table-column label="补货数量" width="200px">
          <template #default="scope">
            <el-input-number v-if="scope.row.sku" v-model="scope.row.calculateTheValue" controls-position="right" :min="1" :max="10" @change="handleChange" />
            <span v-else>货道暂无商品</span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="replenishmentPopUpFrame = false">取 消</el-button>
        <el-button type="primary" @click="submitInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 工单配置 -->
    <el-dialog
      title="工单配置"
      :visible.sync="configureThePopUpBox"
      width="40%"
    >
      <el-input-number v-model="police" controls-position="right" :min="1" :max="10" label="补货警戒线" @change="replenishmentFn" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="configureThePopUpBox = false">取 消</el-button>
        <el-button type="primary" @click="commitThresholdFn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog
      title="工单详情"
      :visible.sync="ticketDetailsDialog"
      width="50%"
    >
      <!-- {{ ticketDetails.taskStatusTypeEntity.statusName }} -->
      <el-link class="elLink" type="primary" :underline="false">{{ ticketDetails.statusName }}</el-link>
      <el-row :gutter="20">
        <el-col :span="12">设备编号:{{ ticketDetails.innerCode }}</el-col>
        <el-col :span="12">创建日期:{{ ticketDetails.createTime }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">取消日期:{{ ticketDetails.updateTime }}</el-col>
        <el-col :span="12">运营人员:{{ ticketDetails.userName }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">工单类型:{{ ticketDetails.typeName }}</el-col>
        <el-col :span="12">补货数量:
          <el-link type="primary" :underline="false" @click.native="viewReplenishmentDetails(ticketDetails.taskId)">补货详情</el-link>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">工单方式: 手动</el-col>
        <el-col :span="12">取消原因:{{ ticketDetails.desc }}</el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="ticketDetailsDialogFn(ticketDetails.taskId,ticketDetails.innerCode)">重新创建</el-button>
      </span>
    </el-dialog>
    <!-- 点击查看补货详情 -->
    <el-dialog
      title="补货详情"
      :visible.sync="replenishmentDetailsPopUpBox"
      width="50%"
      :before-close="turnOffReplenishmentDetails"
    >
      <el-table
        :data="replenishmentInfo"
        style="width: 100%"
        height="500"
      >
        <el-table-column
          prop="channelCode"
          label="货道编号"
        />
        <el-table-column
          prop="skuName"
          label="商品"
        />
        <el-table-column
          prop="expectCapacity"
          label="补货数量"
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import {
  getAllWorkOrderApi,
  // getWorkOrderInfoApi,
  getWorkOrderSearchApi,
  // 根据售货机获取运营人员列表
  getDialogueInfoApi,
  getVendingMachineDetailsApi,
  createATicketApi,
  getReplenishmentCordon,
  setReplenishmentThreshold,
  getTicketDetails,
  // 点击补货详情获取补货信息
  // getAListOfTicketStatuses,
  getReplenishmentDetails
} from '@/api'
export default {
  data() {
    return {
      // 储存补货信息的数据
      replenishmentInfo: '',
      // 点击补货信息展示补货信息数据
      replenishmentDetailsPopUpBox: false,
      // 存储当前点击的工单详情
      ticketDetails: {},
      // 工单详情弹窗
      ticketDetailsDialog: false,
      // 工单警戒线值
      police: '',
      // 工单配置警戒线弹框
      configureThePopUpBox: false,
      // 储存提交的货单信息
      datails: [],
      // 所有货道列表信息
      cargoAisleInfo: [],
      // 点击增加减少的数值
      num: 10,
      // 新增工单弹框
      addATicketDialogBox: false,
      // 补货弹框
      replenishmentPopUpFrame: false,
      // 储存运营人员信息
      operationsStaffs: [],
      // 储存工单类型
      workorderStatus: [],
      // 对话框表单数据
      ruleForm: {
        WorkOrderId: '', // 设备编号
        workorderStatus: '', // 工单类型
        remark: '', // 备注
        operationsStaffsInfo: ''// 储存人员信息
      },
      formRules: {
        WorkOrderId: [{ required: true, message: '请输入', trigger: 'blur' }],
        workorderStatus: [{ required: true, message: ' ', trigger: 'blur' }],
        operationsStaff: [{ required: true, message: ' ', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      // 接收表单数据
      tableData: [],
      formInline: {
        // 工单编号
        WorkOrderId: '',
        // 工单状态
        workorderStatus: ''
      },
      //
      finishdialogVisible: false,
      addFrom: {
        // 页码值
        pageIndex: 1,
        // 一页渲染几条数据
        pageSize: 10,
        // isRepair状态渲染不同的数据
        isRepair: true,
        taskCode: '',
        status: null
      },
      // 一共有多少数据
      total: null
    }
  },
  // 页面进入时获取数据渲染
  created() {
    this.getInfoData()
    this.getworkorderStatus()
  },
  methods: {
    // 关闭补货详情
    turnOffReplenishmentDetails() {
      this.replenishmentDetailsPopUpBox = false
    },
    // 点击补货详情查看补货信息
    async viewReplenishmentDetails(val) {
      this.replenishmentDetailsPopUpBox = true
      const res = await getReplenishmentDetails(val)
      this.replenishmentInfo = res
      console.log(this.replenishmentInfo)
    },
    // 点击详情内的重置表单信息
    async ticketDetailsDialogFn(taskId, innerCode) {
      console.log(taskId)
      console.log(innerCode)
      // 获取运营人员
      const res1 = await getDialogueInfoApi(innerCode)
      // 表单信息
      const res2 = await getTicketDetails(taskId)
      // 补货信息
      const res3 = await getReplenishmentDetails(taskId)
      console.log(res1)
      console.log(res2)
      console.log(res3)
      this.ruleForm.WorkOrderId = res2.innerCode
      this.ruleForm.workorderStatus = res2.taskType.typeName
      this.ruleForm.remark = res2.desc
      this.operationsStaffs = res1
      console.log(this.operationsStaffs)
      this.addATicketDialogBox = true

      this.ticketDetailsDialog = false
    },
    // 设置工单阈值
    async commitThresholdFn() {
      await setReplenishmentThreshold(this.police)
      this.configureThePopUpBox = false
    },
    // 设置补货值
    replenishmentFn(val) {
      this.police = val
    },
    // 工单配置警戒线
    async configureThePopUpBoxFn() {
      this.configureThePopUpBox = true
      const res = await getReplenishmentCordon()
      this.police = res
    },
    // 创建表单提交信息
    async submitFromInfoFn() {
      const temporaryData = {}
      this.tableData.find(item => {
        if (item.userName === this.ruleForm.operationsStaffsInfo) {
          temporaryData.assignorId = item.assignorId
          temporaryData.userId = item.userId
        }
      })
      // 提交表单数据
      await createATicketApi({
        assignorId: temporaryData.assignorId,
        createType: 1,
        desc: this.ruleForm.remark,
        details: this.datails,
        innerCode: this.ruleForm.WorkOrderId,
        productType: 2,
        userId: temporaryData.userId
      })
      this.$refs.ruleForm.resetFields()
      this.addATicketDialogBox = false
    },
    // 提交货单详情信息
    submitInfo() {
      this.cargoAisleInfo.forEach(item => {
        const emptyObject = {}
        if (item.sku) {
          emptyObject.channelCode = item.channelCode
          emptyObject.expectCapacity = item.maxCapacity - item.currentCapacity
          emptyObject.skuId = item.sku.skuId
          emptyObject.skuImage = item.sku.skuImage
          emptyObject.skuName = item.sku.skuName
        } else {
          return
        }
        // 保存要补的货物信息
        this.datails.push(emptyObject)
      })
      // console.log(this.datails)
      this.replenishmentPopUpFrame = false
    },
    // 点击增加减少按钮的回调
    handleChange(value) {
      // console.log(value)
    },
    // 获取自动售货机详细信息
    async getVendingMachineDetailsFn() {
      const res = await getVendingMachineDetailsApi(this.ruleForm.WorkOrderId)
      this.cargoAisleInfo = res
      this.cargoAisleInfo.forEach(item => {
        if (item.sku) {
          item.calculateTheValue = item.maxCapacity - item.currentCapacity
        } else {
          item.calculateTheValue = '-'
        }
        // console.log(item.maxCapacity - item.currentCapacity)
      })
      // console.log(this.cargoAisleInfo)
      this.replenishmentPopUpFrame = true
    },
    // 根据售货机获取运营人员列表
    async getDialogueInfoFn(id) {
      const res = await getDialogueInfoApi(id)
      if (!res) return
      this.operationsStaffs = res
    },
    // 获取工单类型
    async getworkorderStatus() {
      const res = await getAllWorkOrderApi()
      this.workorderStatus = res
    },
    // 获取数据的逻辑
    async getInfoData() {
      const res2 = await getWorkOrderSearchApi(this.addFrom)
      this.tableData = res2.currentPageRecords
      this.total = res2.totalCount - 0
      this.tableData.forEach(item => {
      // 处理createType数据的返回值
        item.createType === 0 ? item.cType = '手动' : item.cType = '自动'
        // 处理时间
        item.createTime = this.putTime(item.createTime)
        // item.createTime = item.createTime.replace(/T/g, ' ')
      })
    },
    // 处理时间
    putTime(val) {
      return dayjs(val).format('YYYY-DD-MM hh:mm:ss')
    },
    // 查询
    inquireFn() {
      this.getInfoData()
    },
    // 失去焦点时获取重新渲染数据
    getAllInfoFn() {
      this.getInfoData()
    },
    detailFn(i) {
      console.log(i)
    },
    addInfo() {
      this.addATicketDialogBox = true
    },
    // 补货订单详细信息
    async seeDetails(val) {
      await getTicketDetails(val.taskId)
      // const res1 = await getAllWorkOrderApi()
      // const res2 = await getAListOfTicketStatuses()
      // console.log(res1)
      // console.log(res2)
      this.ticketDetails = val
      const res = {
        typeName: ''
      }
      const res1 = {
        statusName: ''
      }
      res1.statusName = this.ticketDetails.taskStatusTypeEntity.statusName
      this.ticketDetails.statusName = res1.statusName

      res.typeName = this.ticketDetails.taskType.typeName
      this.ticketDetails.typeName = res.typeName

      console.log(this.ticketDetails.taskType.typeId)
      this.ticketDetailsDialog = true
      // console.log(this.ticketDetails)
    },
    // 分页区域逻辑 pageSize 改变时会触发
    handleSizeChange(newSize) {
      this.addFrom.pageSize = newSize
      this.getInfoData()
    },
    // currentPage 改变时会触发
    handleCurrentChange(newNum) {
      this.addFrom.pageIndex = newNum
      this.getInfoData()
    }

  }
}
</script>

<style scoped lang="scss">
.inputTop{
  margin-top: 12px;
}
.WorkOrderFrom{
  height: 64px;
}
.WorkOrderMain{
  width: 100%;
  height: 100%;
}
.demo-form-inline{
  box-sizing: border-box;
  padding: 0 20px;
  height: 64px;
  margin-bottom: 20px;
  line-height: 64px;
}
::v-deep .el-card__body{
 padding: 0;
}
.WorkOrderInfo{
  margin-top: 20px;
  padding: 20px;

}
.headerTab{
  background-color: #ccc !important;
}
 ::v-deep .el-input__inner{
  width: 203px;
  height: 36px;
 }
 .addInfo{
  background-color: #ef8f4d;
  color: #fff;
  border: 0px solid #000;
 }
 .addInfo:hover{
  background-color: #d4572f;
 }
.dispositionInfo{
  background-color: #faf4f0;
  color: #69615d;
  border: 0px solid #000;
}
.dispositionInfo:hover{
  background-color: #f1e7e2;
 }
 .searchBtn{
  width: 80px;
  height: 36px;
  margin-top: 13px;
  background-color: #6783f7;
 }
 ::v-deep .el-table td,
 ::v-deep .el-table th.is-leaf{
  border: 0px solid #000 ;
 }
 ::v-deep .el-table th.is-leaf{
  background-color: #f4f6fa ;
 }
 ::v-deep .el-table__header-wrapper{
  margin-top: 20px;
  border-radius: 5px;
  overflow: hidden;
 }
.CkText{
  color: #6783f7;
  font-weight: 700;
 }
 .CkText:hover{
  color: #5a72d9;
 }
 .el-pagination{
  margin-top: 20px;
  float: right;
 }
 .dataInfo{
  display: inline-block;
  margin-top: 25px;
  margin-left: 20px;
  font-size: 14px;
  font-weight: 700;
  color: #ccc;
 }
 ::v-deep .el-dialog{
  overflow: hidden;
  border-radius: 10px;
 }
 ::v-deep .el-dialog__header{
  background-color: #fff;
}
::v-deep .el-dialog__title{
  color: #000;
}
::v-deep .el-input__inner{
  width: 180px;
}
::v-deep .el-dialog__body{
  padding: 0 20px;
}
.el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .elLink{
   margin: 20px 0;
  }
  ::v-deep .el-dialog__header .el-icon-close:before{
    color: #000;
  }
</style>
